//
//  ZZLetterDetailController.m
//  QQplayground
//
//  Created by zhangxy on 2018/8/15.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZLetterDetailController.h"


#import "ZZKeyboardView.h"
#import "UserInfoController.h"

#import "ZZLetterCell.h"
#define cellIdentifier @"ZZLetterCell"

#import "ZZShareView.h"

@interface ZZLetterDetailController ()<ZZTopicCellDelegate,UIGestureRecognizerDelegate>{
    NSString *image_id;
}

@property(nonatomic,strong)  NSMutableArray *listArray;
@property(nonatomic,strong)  UITableView *listTable;

@property(nonatomic,strong)  ZZKeyboardView   *keyboardView;

@end

@implementation ZZLetterDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = convertToString(_model.user_info.user_name);
    [self setNavigationBar];
    
    self.navigationController.navigationBarHidden = NO;
    
    [self.view setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    [self createTableView];
    
    
    
    _keyboardView = [[ZZKeyboardView alloc] initWithDelegate:self changeView:_listTable show:NO style:ZZKeyboardControlsDefault];
    __weak ZZLetterDetailController *saveSelf = self;
    [_keyboardView setResultBlock:^(int code,NSString *text,id replayModel){
        if(code == 0){
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            [dict setObject:convertToString(_model.user_info.user_id) forKey:@"user_id"];
            [dict setObject:convertToString([UserUtil getUser].user_id) forKey:@"session_uid"];
            [dict setObject:convertToString(text) forKey:@"message"];
           
            
            [NetworkUtil POST:API_SendMessage parameters:dict success:^(id responseObject, NSDictionary *dict) {
                LetterEntity *addModel = [LetterEntity new];
                addModel.from_user_info = [UserUtil getUser];
                addModel.to_user_info = _model.user_info;
                addModel.message = text;
                addModel.add_time = @"刚刚";
                addModel.n_id = dict[@"data"][@"message_id"];
                [saveSelf.listArray addObject:addModel];
                [saveSelf.listTable reloadData];
                
                [self scrollTableToBottom];
            } failure:^(NSError *error, NSString *message) {
                [PopUtil showMessage:message];
            }];
        }
    }];
    
    
    
    UITapGestureRecognizer *oneTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pageClick:)];
    oneTap.delegate = self;
    oneTap.numberOfTouchesRequired = 1;
    [self.view addGestureRecognizer:oneTap];
}



-(void)pageClick:(UITapGestureRecognizer *) tap{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    [_keyboardView hideKeyboard];
}


-(void)createTableView{
    _listArray = [[NSMutableArray alloc] init];
    
    _listTable=[self.view createTableView:self cell:cellIdentifier formY:0 withHeight:self.view.bounds.size.height-BottomHeight];
    
    [_listTable setBackgroundColor:UIColorFromRGB(BgSystemColor)];
    
    if (iOS7) {
        _listTable.backgroundView = nil;
    }
    
    [_listTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    
    [self setTableSeparatorInset];
    
    
    MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
        [self loadBegin];
    }];
    _listTable.header = header;
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self loadBegin];
}



#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
    NSLog(@"%@", NSStringFromClass([touch.view class]));
    // 判断轮播图点击
     if ([NSStringFromClass([touch.view class]) isEqualToString:@"ZCTTMLEmojiLabel"]) {
        [self pageClick:nil];
        return NO;
    }
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        [_keyboardView hideKeyboard];
        return NO;
    }
    return  YES;
}



-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [_keyboardView hideKeyboard];
}

-(void)loadBegin{
    [self loadMoreData];
}


-(void)onCellItemClick:(ZZTopicCellClickType)type obj:(id)senderObj{
    
    [ZZCoreTools sucaiListenerImpl:senderObj type:type page:self refresh:_listTable];
}

/**
 加载更多
 */
-(void)loadMoreData{
    NSString *message_id = @"";
    if(_listArray.count > 0){
        LetterEntity *mesage = [_listArray firstObject];
        message_id = mesage.n_id;
    }
    NSDictionary *p = @{@"user_id":_model.user_info.user_id,
                        @"session_uid":[UserUtil getUser].user_id,
                        @"derection":@"up",
                        @"message_id":message_id,
                        };
    [NetworkUtil POST:API_GetSessiondetail parameters:p success:^(id responseObject, NSDictionary *dictionary) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
        NSMutableArray *messages = [[NSMutableArray alloc] init];
        
        NSArray *arr = dictionary[@"data"][@"list"];
        for(NSDictionary *item in arr){
            if([item isKindOfClass:[NSDictionary class]]){
                LetterEntity *model = [[LetterEntity alloc] initWithDictionary:item];
                
                [messages addObject:model];
            }
        }
        if(messages && messages.count>0){
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:
                                    NSMakeRange(0,[messages count])];
            
            [_listArray insertObjects:messages atIndexes:indexSet];
        }
        [self.listTable reloadData];
        
        
        if([@"" isEqual:message_id]){
            [self scrollTableToBottom];
        }
    } failure:^(NSError *error, NSString *message) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if([self.listTable.header isRefreshing]){
            [self.listTable.header endRefreshing];
        }
        if([self.listTable.footer isRefreshing]){
            [self.listTable.footer endRefreshing];
        }
    }];
}



#pragma mark UITableView delegate Start
// 返回section数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

// 返回section高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1f;
}

// 返回section 的View
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 54)];
    [headerView setBackgroundColor:UIColor.whiteColor];
    
    
    return headerView;
}


// 返回section下得行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
//    [tableView setContentOffset:CGPointMake(0, tableView.contentSize.height-tableView.frame.size.height) animated:NO];
    return _listArray.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ZZLetterCell *cell = (ZZLetterCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[ZZLetterCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    cell.delegate = self;
    [cell dataToView:_listArray[indexPath.row]];
    
    return cell;
}



// 是否显示删除功能
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

// 删除清理数据
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    editingStyle = UITableViewCellEditingStyleDelete;
}


// table 行的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //    return 70.0f;
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

// table 行的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}

//设置分割线间距
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if((indexPath.row+1) < _listArray.count){
        UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
        if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
            [cell setSeparatorInset:inset];
        }
        
        if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
            [cell setLayoutMargins:inset];
        }
    }
}

/**
 显示消息到TableView上
 */
-(void)scrollTableToBottom{
    NSInteger s = [self.listTable numberOfSections];  //有多少组
    if (s<1) return;  //无数据时不执行 要不会crash
    NSInteger r = [self.listTable numberOfRowsInSection:s-1]; //最后一组有多少行
    if (r<1) return;
    NSIndexPath *ip = [NSIndexPath indexPathForRow:r-1 inSection:s-1];  //取最后一行数据
    [self.listTable scrollToRowAtIndexPath:ip atScrollPosition:UITableViewScrollPositionBottom animated:YES]; //滚动到最后一行
}


-(void)viewDidLayoutSubviews{
    [self setTableSeparatorInset];
}
#pragma mark UITableView delegate end

/**
 *  设置UITableView分割线空隙
 */
-(void)setTableSeparatorInset{
    UIEdgeInsets inset = UIEdgeInsetsMake(0, 10, 0, 0);
    if ([_listTable respondsToSelector:@selector(setSeparatorInset:)]) {
        [_listTable setSeparatorInset:inset];
    }
    
    if ([_listTable respondsToSelector:@selector(setLayoutMargins:)]) {
        [_listTable setLayoutMargins:inset];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
